package com.niit.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.niit.chat.dto.SessionVO;
import com.niit.chat.entity.Session;
import com.niit.chat.entity.Message;
import com.niit.chat.mapper.SessionMapper;
import com.niit.chat.mapper.MessageMapper;
import com.niit.chat.mapper.UserMapper;
import com.niit.chat.service.SessionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SessionServiceImpl implements SessionService {
    
    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Session> listSessions() {
        LambdaQueryWrapper<Session> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Session::getDeleted, 0)
               .orderByDesc(Session::getLastMessageTime);
        return sessionMapper.selectList(wrapper);
    }

    @Override
    public Session getSessionById(Long id) {
        return sessionMapper.selectById(id);
    }

    @Override
    public List<Session> listSessionsByUser(Long userId) {
        // 1. 查出所有会话关系（userId, friendId）
        List<Session> sessions = sessionMapper.selectList(
            new LambdaQueryWrapper<Session>()
                .eq(Session::getUserId, userId)
                .eq(Session::getDeleted, 0)
        );
        for (Session session : sessions) {
            // 2. 对每个会话，查 tb_message 表最新一条未撤回/未删除/未单方删除的消息
            LambdaQueryWrapper<Message> msgWrapper = new LambdaQueryWrapper<>();
            msgWrapper.and(w -> w
                    .eq(Message::getSenderId, userId).eq(Message::getReceiverId, session.getFriendId()).eq(Message::getDeletedBySender, 0)
                    .or()
                    .eq(Message::getSenderId, session.getFriendId()).eq(Message::getReceiverId, userId).eq(Message::getDeletedByReceiver, 0)
            )
            .eq(Message::getIsRecalled, 0)
            .eq(Message::getIsDeleted, 0)
            .orderByDesc(Message::getSendDate)
            .last("LIMIT 1");
            Message lastMsg = messageMapper.selectOne(msgWrapper);
            if (lastMsg != null) {
                if (lastMsg.getType() == 1) {
                    session.setLastMessage("[图片]");
                } else if (lastMsg.getType() == 2) {
                    session.setLastMessage("[视频]");
                } else {
                    session.setLastMessage(lastMsg.getContent());
                }
                session.setLastMessageTime(lastMsg.getSendDate());
            } else {
                session.setLastMessage("暂无消息");
                session.setLastMessageTime(null);
            }
        }
        // 3. 按 lastMessageTime 排序
        sessions.sort((a, b) -> {
            if (a.getLastMessageTime() == null && b.getLastMessageTime() == null) return 0;
            if (a.getLastMessageTime() == null) return 1;
            if (b.getLastMessageTime() == null) return -1;
            return b.getLastMessageTime().compareTo(a.getLastMessageTime());
        });
        return sessions;
    }

    @Override
    public void createSession(Session session) {
        sessionMapper.insert(session);
    }

    @Override
    public void updateSession(Session session) {
        sessionMapper.updateById(session);
    }

    @Override
    public List<SessionVO> getUserSessions(Long userId) {
        LambdaQueryWrapper<Session> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Session::getUserId, userId);
        List<Session> sessions = sessionMapper.selectList(wrapper);
        if (sessions == null || sessions.isEmpty()) {
            return Collections.emptyList();
        }
        return sessions.stream().map(session -> {
            SessionVO vo = new SessionVO();
            BeanUtils.copyProperties(session, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public SessionVO getSession(Long userId, Long friendId) {
        LambdaQueryWrapper<Session> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Session::getUserId, userId).eq(Session::getFriendId, friendId);
        Session session = sessionMapper.selectOne(wrapper);
        if (session == null) {
            return null;
        }
        SessionVO sessionVO = new SessionVO();
        BeanUtils.copyProperties(session, sessionVO);
        return sessionVO;
    }

    @Override
    public void deleteSession(Long id) {
        Session session = new Session();
        session.setId(id);
        session.setDeleted(1);
        sessionMapper.updateById(session);
    }
} 